package com.unidt.www.module.expert.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.unidt.www.framework.common.pojo.PageResult;
import com.unidt.www.framework.common.util.number.OrganIdUtils;
import com.unidt.www.framework.common.util.object.ConvertUtil;
import com.unidt.www.framework.common.util.string.PingYinUtil;
import com.unidt.www.framework.common.util.validation.EntityValidationUtils;
import com.unidt.www.framework.common.util.validation.ValidationResult;
import com.unidt.www.module.expert.domain.ExpertInfoDo;
import com.unidt.www.module.expert.form.ExpertInfoEditForm;
import com.unidt.www.module.expert.form.ExpertInfoQueryForm;
import com.unidt.www.module.expert.mapper.ExpertInfoMapper;
import com.unidt.www.module.expert.service.IExpertInfoService;
import com.unidt.www.module.expert.vo.*;
import com.unidt.www.module.system.dal.dataobject.organ.OrganCodeDo;
import com.unidt.www.module.system.dal.mysql.organ.OrganCodeMapper;
import com.unidt.www.module.system.dal.vo.OrganCodeVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author sk
 * @Description:
 * @Date 2022/11/16 13:35
 **/
@Service
@Slf4j
public class ExpertInfoServiceImpl implements IExpertInfoService {

    @Autowired
    ExpertInfoMapper expertInfoMapper;

    @Autowired
    OrganCodeMapper organCodeMapper;

    @Override
    public PageResult<ExpertInfoDo> queryPage(ExpertInfoQueryForm queryForm) {

        /**
         * 是否和租户有关系  待确认
         */
        return this.expertInfoMapper.selectPage(queryForm, makeWrapper(queryForm));
    }

    @Override
    public Boolean delete(Long id) {

        /**
         * 要确定是不是软删除
         */
        this.expertInfoMapper.deleteById(id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean edit(ExpertInfoEditForm expertInfoEditForm) {

        /**
         * 新增编辑在 放在一个方法接口
         */
        ExpertInfoDo expertInfoDo = new ExpertInfoDo();


        BeanUtil.copyProperties(expertInfoEditForm, expertInfoDo);
        String expertName = expertInfoDo.getName();
        String firstName = PingYinUtil.getFirst(expertName);
        expertInfoDo.setFirstName(firstName);
        if (Objects.isNull(expertInfoDo.getId())) {
            this.expertInfoMapper.insert(expertInfoDo);
        } else {
            this.expertInfoMapper.updateById(expertInfoDo);
        }
        return true;
    }

    @Override
    public List<ExpertInfoDo> getList() {
        return this.expertInfoMapper.selectList();
    }

    /**
     * 功能描述: 获取热门标签 后期九可以放入换成
     *
     * @param
     * @return java.util.List<com.unidt.www.module.expert.vo.ExpertTag>
     * @author sk
     * @date 2022/12/8
     */
    @Override
    public List<AreaExpertiseVo> getHotAreaExpertise() {

        /**
         * 取出所有专家
         */
        List<ExpertInfoDo> allList = this.expertInfoMapper.selectList();

        /**
         * 所有领域
         */
        List<String> tagsList = new ArrayList<>();

        List<AreaExpertiseVo> expertTagList = new ArrayList<>();

        Map<String, AreaExpertiseVo> expertTagMap = new HashMap<>();

        if (!allList.isEmpty()) {
            allList.forEach(e -> {
                String tags = e.getAreaExpertise();
                if (StringUtils.isNotBlank(tags)) {
                    String[] tagArray = tags.split("[,]");
                    for (Integer i = 0; i < tagArray.length; i++) {
                        tagsList.add(tagArray[i]);
                    }
                }
            });
        }
        /**
         * 根据标签内容去重 并且记录标签数量
         */
        if (!tagsList.isEmpty()) {
            tagsList.forEach(t -> {
                AreaExpertiseVo expertTag = expertTagMap.get(t);
                if (Objects.isNull(expertTag)) {
                    expertTag = new AreaExpertiseVo(t, 1);
                    expertTagMap.put(t, expertTag);
                } else {
                    expertTag.setCount(expertTag.getCount() + 1);
                }

            });
        }
        if (!expertTagMap.isEmpty()) {
            expertTagList = expertTagMap.values().stream().collect(Collectors.toList());

            /**
             * 根据count倒排 取前5
             */
            expertTagList = expertTagList.stream().sorted(Comparator.comparing(AreaExpertiseVo::getCount).reversed()).collect(Collectors.toList());

            Integer size = expertTagList.size();
            if (size >= 5) {
                return expertTagList.subList(0, 4);
            } else {
                return expertTagList;

            }
        }

        return new ArrayList<>();
    }

    @Override
    public ExpertInfoVo getDetail(Long id) {
        ExpertInfoDo expertInfoDo = this.expertInfoMapper.selectById(id);

        ExpertInfoVo expertInfoVo = ConvertUtil.convert(expertInfoDo, ExpertInfoVo.class);
        Long organId = expertInfoVo.getOrganId();
        if (Objects.nonNull(organId)) {
            OrganCodeDo organCodeDo = this.organCodeMapper.selectById(organId);
            if (Objects.nonNull(organCodeDo)) {
                expertInfoVo.setOrganName(organCodeDo.getName());
                List<Long> organIds = OrganIdUtils.getAllOrganIds(organId);
                List<OrganCodeDo> organCodeDos = this.organCodeMapper.selectBatchIds(organIds);
                expertInfoVo.setOrganList(ConvertUtil.convertList(organCodeDos, OrganCodeVo.class));
            }

        }
        return expertInfoVo;
    }

    @Override
    public Boolean deleteBatch(List<Long> ids) {
        this.expertInfoMapper.deleteBatchIds(ids);
        return true;
    }

    @Override
    public void saveBatch(List<ExpertInfoDo> list) {
        this.saveBatch(list);
    }

    @Override
    public ExpertImportResult importData(List<ExpertInfoExcelVo> excelFormList) {
        Integer totalCount = excelFormList.size();

        ExpertImportResult result = new ExpertImportResult();
        List<ExpertInfoDo> list = new ArrayList<>();
        List<ExpertImportErrorVo> errorList = new ArrayList<>();

        for(Integer i=0;i<excelFormList.size();i++){
            ExpertInfoExcelVo e = excelFormList.get(i);
            Integer rowNo = i+1;
            ExpertImportErrorVo expertImportErrorVo =
                    new ExpertImportErrorVo(rowNo);

            /**
             * 数据必填项验证
             */
            ValidationResult validationResult = EntityValidationUtils.validateEntity(e);
            if (!validationResult.isHasErrors()) {
                ExpertInfoDo expertInfoDo = ConvertUtil.convert(e, ExpertInfoDo.class);
                String gender = e.getGender();
                if ("男".equals(gender)) {
                    expertInfoDo.setGender(1);
                } else {
                    expertInfoDo.setGender(2);
                }
                /**
                 * 根据身份证号码验证数据是否已经存在
                 */

                String idCard = expertInfoDo.getIdCard();

                Long count = this.expertInfoMapper.countByIdCard(idCard);
                if (Long.valueOf(0).equals(count)) {
                    list.add(expertInfoDo);
                } else {
                    expertImportErrorVo.setErrorMessage("身份证"+idCard+"已经存在");
                    errorList.add(expertImportErrorVo);
                    log.error("idCard:{} 已经存在", idCard);
                }

            }else {
                expertImportErrorVo.setErrorMessage(validationResult.getErrorMsg().values().toString());
                errorList.add(expertImportErrorVo);
            }
        }



        if (!list.isEmpty()) {
            this.expertInfoMapper.insertBatch(list);
        }
        Integer successCount = list.size();
        Integer failCount = totalCount - successCount;
        result.setTotalCount(totalCount);
        result.setSuccessCount(successCount);
        result.setFailCount(failCount);
        result.setErrorList(errorList);
        return result;
    }

    @Override
    public List<ExpertInfoExcelVo> queryAll(ExpertInfoQueryForm queryForm) {
        /**
         * 查出专家
         */
        List<ExpertInfoDo> list = this.expertInfoMapper.selectList(this.makeWrapper(queryForm));
        if (!list.isEmpty()) {
            List<Long> organIds = list.stream().filter(e -> e.getOrganId() != null)
                    .map(ExpertInfoDo::getOrganId).collect(Collectors.toList());
            /**
             * 填充区域名称
             */
            Map<Long, OrganCodeDo> organCodeMap = this.organCodeMapper.getMapByIds(organIds);
            List<ExpertInfoExcelVo> dataList = ConvertUtil.convertList(list, ExpertInfoExcelVo.class);
            if (!dataList.isEmpty()) {
                dataList.forEach(d -> {
                    Long organId = d.getOrganId();
                    if (Objects.nonNull(organId)) {
                        OrganCodeDo organCodeDo = organCodeMap.get(organId);
                        if (Objects.nonNull(organCodeDo)) {
                            d.setOrganName(organCodeDo.getName());
                        }
                    }
                });
            }
            return dataList;
        }

        return new ArrayList<>();


    }

    @Override
    public List<String> getTags() {
        /**
         * 取出所有专家
         */
        List<ExpertInfoDo> allList = this.expertInfoMapper.selectList();

        /**
         * 标签
         */
        List<String> tagsList = new ArrayList<>();

        if (!allList.isEmpty()) {
            allList.forEach(e -> {
                String tags = e.getTags();
                if (StringUtils.isNotBlank(tags)) {
                    String[] tagArray = tags.split("[,]");
                    for (Integer i = 0; i < tagArray.length; i++) {
                        tagsList.add(tagArray[i]);
                    }
                }
            });
        }
        return tagsList;

    }

    @Override
    public List<String> getAreaExpertise() {
        /**
         * 取出所有专家
         */
        List<ExpertInfoDo> allList = this.expertInfoMapper.selectList();

        /**
         * 标签
         */
        List<String> areaExpertiseList = new ArrayList<>();

        if (!allList.isEmpty()) {
            allList.forEach(e -> {
                String tags = e.getAreaExpertise();
                if (StringUtils.isNotBlank(tags)) {
                    String[] tagArray = tags.split("[,]");
                    for (Integer i = 0; i < tagArray.length; i++) {
                        areaExpertiseList.add(tagArray[i]);
                    }
                }
            });
        }
        return areaExpertiseList;
    }

    private LambdaQueryWrapper<ExpertInfoDo> makeWrapper(ExpertInfoQueryForm queryForm) {
        LambdaQueryWrapper<ExpertInfoDo> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        Integer queryProperty = queryForm.getQueryProperty();
        String propertyValue = queryForm.getPropertyValue();
        if (StringUtils.isNotBlank(propertyValue) || (queryProperty != null && queryProperty != 0)) {
            if (new Integer(1).equals(queryProperty)) {
                /**
                 * 姓名
                 */
                lambdaQueryWrapper.like(ExpertInfoDo::getName, propertyValue);
            } else if (new Integer(2).equals(queryProperty)) {
                /**
                 * 专业背景
                 */
                lambdaQueryWrapper.like(ExpertInfoDo::getMajor, propertyValue);
            } else if (new Integer(3).equals(queryProperty)) {
                /**
                 * 毕业院校
                 */
                lambdaQueryWrapper.like(ExpertInfoDo::getGraduateSchool, propertyValue);
            } else if (new Integer(4).equals(queryProperty)) {
                /**
                 * 所在单位
                 */
                lambdaQueryWrapper.like(ExpertInfoDo::getUnitName, propertyValue);
            } else if (new Integer(5).equals(queryProperty)) {
                /**
                 * 标签
                 */
                lambdaQueryWrapper.like(ExpertInfoDo::getTags, propertyValue);
            } else if (new Integer(6).equals(queryProperty)) {
                /**
                 * 标签
                 */
                lambdaQueryWrapper.like(ExpertInfoDo::getAreaExpertise, propertyValue);
            }
        }
        lambdaQueryWrapper.orderByAsc(ExpertInfoDo::getFirstName);
        lambdaQueryWrapper.orderByDesc(ExpertInfoDo::getCreateTime);
        return lambdaQueryWrapper;
    }
}
